<?php
namespace Service;

class TokenBucket extends Base
{
    /*
        redis列表的名称
    */
    private $listName = 'test';

    /*
        桶内的最大令牌数目
    */
    private $max = 5;

    private $redis = null;

    public function init()
    {
        $redis = $this->get(CACHE_TOKENBUCKET)->getRedis();
        return $this->setRedis($redis);
    }

    private function setRedis($redis)
    {
        $this->redis = $redis;
        return $this;
    }

    public function add($n = 0)
    {

        $size = $this->redis->lSize($this->listName);
        $span = $this->max - $size;
        if($n > $span){
            $n = $span;
        }
        if($n > 0){
            $token = array_fill(0, $n, 1);
            $this->redis->lPush($this->listName, ...$token);
            return $n;
        }
        return 0;
    }

    public function getToken()
    {
        return $this->redis->rPop($this->listName);
    }

    public function reset()
    {
        $this->redis->delete($this->listName);
        $this->add($this->max);
    }

}